from pyfzf.pyfzf import FzfPrompt
import sys
import os
from config import player

fzf = FzfPrompt()
addition_menu_items = {
    "exit": "Exit",
    "level_up": "Level Up"
}


def terminate():
    print("EXIT")
    sys.exit()


def item_do(item):
    os.system(f"{player} {item}")


def show_menu(channels, video_titles, links):
    """Just 2 levels menu. Displays channels list and video titles in channels"""

    #  appending additional menu items like Exit and level up
    channels.append(addition_menu_items["exit"])
    for item in video_titles:
        item.append(addition_menu_items["level_up"])

    def main_menu():
        main_choice = fzf.prompt(channels, '--cycle')

        try:
            if main_choice[0] == addition_menu_items["exit"]:
                return terminate()
            else:
                return channels.index(main_choice[0])
        except IndexError:
            return None

    main_index = main_menu()

    while True:
        if main_index is None:
            main_index = main_menu()

        item_choice = fzf.prompt(video_titles[main_index], '--cycle')
        try:
            if item_choice[0] != addition_menu_items["level_up"]:
                item_index = video_titles[main_index].index(item_choice[0])
                link = links[main_index][item_index]
                item_do(link)
            else:
                main_index = None
        except IndexError:
            pass

